package cn.xlbweb.sso.controller;

import cn.xlbweb.sso.server.ServerResponse;
import cn.xlbweb.sso.service.IClientService;
import cn.xlbweb.sso.service.IServerService;
import cn.xlbweb.sso.service.IUserService;
import eu.bitwalker.useragentutils.Browser;
import eu.bitwalker.useragentutils.OperatingSystem;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.UUID;

/**
 * @author: bobi
 * @date: 2019-03-09 17:32
 * @description:
 */
@Slf4j
@RestController
public class LoginController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IServerService iServerService;

    @Autowired
    private IClientService iClientService;

    @GetMapping("login")
    public ModelAndView login(String redirectUrl, HttpSession session) {
        String token = (String) session.getAttribute("token");
        // 表明用户已经在sso server登陆过
        if (StringUtils.isNotEmpty(token)) {
            ModelAndView modelAndView = new ModelAndView("redirect:" + redirectUrl);
            modelAndView.addObject("token", token);
            return modelAndView;
        } else {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.addObject("redirectUrl", redirectUrl);
            modelAndView.setViewName("/login");
            return modelAndView;
        }
    }

    @PostMapping("login")
    public ServerResponse login(String username, String password, String redirectUrl, HttpSession session, HttpServletRequest request) {
        ServerResponse serverResponse = iUserService.login(username, password);
        if (serverResponse.isSuccess()) {
            // 登陆标识
            String token = UUID.randomUUID().toString();
            session.setAttribute("token", token);
            session.setAttribute("user", serverResponse.getData());
            // 记录子系统信息
            if (StringUtils.isNotBlank(redirectUrl)) {
                UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
                Browser browser = userAgent.getBrowser();
                OperatingSystem os = userAgent.getOperatingSystem();
                iServerService.save(token, browser.getName(), os.getName());
                return ServerResponse.success("登陆成功", token);
            }
            return ServerResponse.success("登陆成功");
        }
        return ServerResponse.error("登陆失败，账号或密码错误！");
    }

    @GetMapping("verifyToken")
    public Boolean verifyToken(String token, String clientUrl, String jessionId, Integer projectId) {
        Boolean result = iServerService.existsByToken(token);
        if (result) {
            iClientService.save(token, jessionId, clientUrl, projectId);
        }
        return result;
    }

    @GetMapping("logout")
    public ModelAndView logout(HttpSession session, String redirectUrl) {
        session.invalidate();
        ModelAndView modelAndView = new ModelAndView("redirect:/login");
        modelAndView.addObject("redirectUrl", redirectUrl);
        return modelAndView;
    }
}
